<template>
  <div class="ai-assistant">
    <!-- 可拖动的悬浮按钮 -->
    <div
        class="ai-button"
        :style="{ left: buttonPosition.left + 'px', top: buttonPosition.top + 'px' }"
        @mousedown="startDrag"
        @click="toggleChat"
    >
      <!-- 用图片代替AI助手图标 -->
      <img src="@/assets/AI.jpg" alt="AI助手图标" class="ai-icon">
    </div>

    <!-- 聊天对话框 -->
    <div
        class="chat-dialog"
        v-if="showChat"
        :style="{ right: '20px', bottom: buttonPosition.height + 30 + 'px' }"
    >
      <div class="dialog-header">
        <div class="header-title">AI助手</div>
        <el-icon class="close-btn" @click="toggleChat"><Close /></el-icon>
      </div>

      <div class="dialog-body">
        <!-- 左侧会话列表 -->
        <div class="conversation-list">
          <el-button
              class="new-conversation-btn"
              type="primary"
              @click="createNewConversation"
          >
            <el-icon><Plus /></el-icon>
            新会话
          </el-button>

          <div class="conversation-items">
            <div
                v-for="conv in conversations"
                :key="conv.conversationId"
                class="conversation-item"
                :class="{ 'active': currentConversationId === conv.conversationId }"
                @click="switchConversation(conv.conversationId)"
            >
              <div class="conv-title">
                {{ conv.title }}
                <el-icon
                    class="delete-conv"
                    @click.stop="deleteConversation(conv.conversationId)"
                >
                  <Delete />
                </el-icon>
              </div>
              <div class="conv-preview">
                {{ getLastMessagePreview(conv) }}
              </div>
            </div>
          </div>
        </div>

        <!-- 右侧聊天区域 -->
        <div class="chat-area" v-if="currentConversationId">
          <div class="chat-messages">
            <!-- 聊天消息列表 -->
            <div
                class="message"
                v-for="(msg, index) in currentMessages"
                :key="index"
                :class="{ 'user-message': msg.isUser, 'ai-message': !msg.isUser }"
            >
              <div class="message-avatar">
                <el-icon v-if="msg.isUser"><User /></el-icon>
                <!-- 用图片代替AI头像 -->
                <img v-else src="@/assets/AI.jpg" alt="AI头像" class="avatar-img">
              </div>
              <div class="message-content">{{ msg.content }}</div>
            </div>

            <!-- 加载状态 -->
            <div class="message ai-message" v-if="isLoading">
              <div class="message-avatar">
                <img src="@/assets/AI.jpg" alt="AI头像" class="avatar-img">
              </div>
              <div class="message-content typing-indicator">
                <span class="dot"></span>
                <span class="dot"></span>
                <span class="dot"></span>
              </div>
            </div>
          </div>

          <div class="message-input">
            <el-input
                v-model="inputMessage"
                placeholder="输入您的问题..."
                @keyup.enter="sendMessage"
                clearable
                :disabled="!currentConversationId"
                ref="messageInput"
            ></el-input>
            <el-button
                class="send-btn"
                type="primary"
                @click="sendMessage"
                :disabled="!inputMessage.trim() || isLoading || !currentConversationId"
            >
              <el-icon><Top /></el-icon>
            </el-button>
          </div>
        </div>

        <div class="empty-state" v-else>
          <img src="@/assets/AI.jpg" alt="AI助手" class="empty-icon">
          <p>请选择或创建一个会话</p>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted, nextTick, watch, getCurrentInstance } from 'vue'
import { User, Close, Send, Delete, Plus } from '@element-plus/icons-vue'
import { ElIcon, ElButton, ElInput, ElMessage } from 'element-plus'
import Request from '@/utils/request'

// 获取组件实例
const instance = getCurrentInstance()

const userInfo = ref(JSON.parse(localStorage.getItem('frontUser') || localStorage.getItem('backUser') || '{}'));
const userId = ref(userInfo.value.id)

// 聊天状态
const showChat = ref(false)
const currentConversationId = ref('')
const conversations = ref([])
const currentMessages = ref([])
const inputMessage = ref('')
const isLoading = ref(false)
const messageInput = ref(null)

// 按钮位置和尺寸
const buttonPosition = ref({
  left: 0,
  top: 0,
  width: 60,
  height: 60
})

// 拖动状态
const isDragging = ref(false)
const dragOffset = ref({ x: 0, y: 0 })

// 切换聊天框显示/隐藏
const toggleChat = () => {
  showChat.value = !showChat.value
  if (showChat.value) {
    loadConversations()
  }
}

// 加载会话列表
const loadConversations = async () => {
  try {
    const res = await Request.get(`/chat/list/${userId.value}`)
    if (res && Array.isArray(res)) {
      conversations.value = res.map(conv => {
        // 确保每个会话都有必要的字段
        return {
          conversationId: conv.conversationId || conv.id,
          title: conv.title || '新会话',
          aimessages: conv.aimessages || [],
          preview: conv.preview || ''
        }
      })
      // 如果有会话，默认选中第一个
      if (conversations.value.length > 0 && !currentConversationId.value) {
        switchConversation(conversations.value[0].conversationId)
      }
    } else {
      conversations.value = []
    }
  } catch (error) {
    console.error('加载会话列表失败:', error)
    ElMessage.error('加载会话列表失败，请重试')
  }
}

// 创建新会话 - 修复字段匹配问题
const createNewConversation = async () => {
  try {
    isLoading.value = true
    const res = await Request.post('/chat/new', {}, {
      params: { userId: userId.value }
    })

    // 后端返回的是conversationId而不是id，这里进行修正
    if (res && (res.conversationId || res.id)) {
      const conversationId = res.conversationId || res.id;
      const newConversation = {
        conversationId: conversationId,
        title: '新会话',
        aimessages: [],
        preview: ''
      };

      // 确保新会话添加到列表并切换
      conversations.value.unshift(newConversation)
      // 强制刷新
      conversations.value = [...conversations.value]
      // 切换到新会话
      switchConversation(conversationId)

      // 自动聚焦到输入框
      nextTick(() => {
        if (messageInput.value) {
          messageInput.value.focus()
        }
      })

      ElMessage.success('新会话创建成功')
    } else {
      ElMessage.error('创建会话失败，返回数据无效')
      console.error('创建会话失败，返回数据无效:', res)
    }
  } catch (error) {
    console.error('创建新会话失败:', error)
    ElMessage.error(`创建会话失败: ${error.message || '未知错误'}`)
  } finally {
    isLoading.value = false
  }
}

// 切换会话
const switchConversation = async (conversationId) => {
  if (!conversationId) return

  currentConversationId.value = conversationId
  isLoading.value = true
  currentMessages.value = [] // 清空当前消息，避免显示旧内容

  try {
    const res = await Request.get(`/chat/history/${userId.value}/${conversationId}`)
    if (res && Array.isArray(res.aimessages)) {
      // 过滤掉系统消息，并将后端角色信息转换为isUser字段
      currentMessages.value = res.aimessages
          .filter(msg => msg.role !== 'system')
          .map(msg => ({
            content: msg.content,
            isUser: msg.role === 'user' // 将role转换为isUser布尔值
          }))
      scrollToBottom()

      // 聚焦到输入框
      nextTick(() => {
        if (messageInput.value) {
          messageInput.value.focus()
        }
      })
    } else {
      currentMessages.value = []
      ElMessage.warning('该会话没有历史消息')
    }
  } catch (error) {
    console.error('获取会话历史失败:', error)
    ElMessage.error('获取会话历史失败，请重试')
  } finally {
    isLoading.value = false
  }
}

// 删除会话
const deleteConversation = async (conversationId) => {
  try {
    const res = await Request.delete(`/chat/delete/${userId.value}/${conversationId}`)
    if (res) {
      // 如果删除的是当前会话，清空聊天区域
      if (currentConversationId.value === conversationId) {
        currentConversationId.value = ''
        currentMessages.value = []
      }
      // 从列表中移除
      conversations.value = conversations.value.filter(conv => conv.conversationId !== conversationId)
      ElMessage.success('会话已删除')
    }
  } catch (error) {
    console.error('删除会话失败:', error)
    ElMessage.error('删除会话失败，请重试')
  }
}

// // 发送消息 - 修改为使用POST请求进行流式输出
// const sendMessage = async () => {
//   const content = inputMessage.value.trim()
//   if (!content || isLoading.value || !currentConversationId.value) return
//
//   // 添加用户消息
//   const userMessage = {
//     content,
//     isUser: true
//   }
//   currentMessages.value.push(userMessage)
//
//   inputMessage.value = ''
//   isLoading.value = true
//   scrollToBottom()
//
//   try {
//     // 创建AI消息占位符
//     const aiMessageIndex = currentMessages.value.length;
//     const aiMessage = {
//       content: '',
//       isUser: false
//     }
//     currentMessages.value.push(aiMessage)
//     scrollToBottom()
//
//     // 使用Fetch API发送POST请求
//     const response = await fetch('/api/chat/stream-send', {
//       method: 'POST',
//       headers: {
//         'Content-Type': 'application/json',
//       },
//       body: JSON.stringify({
//         userId: userId.value,
//         conversationId: currentConversationId.value,
//         message: content
//       })
//     })
//
//     if (!response.ok) {
//       throw new Error(`HTTP error! status: ${response.status}`)
//     }
//
//     const reader = response.body.getReader()
//     const decoder = new TextDecoder('utf-8')
//     let fullResponse = ''
//     let buffer = '' // 用于存储不完整的数据块
//
//     while (true) {
//       const { done, value } = await reader.read()
//       if (done) {
//         break
//       }
//
//       // 将当前块与缓冲区连接
//       buffer += decoder.decode(value, { stream: true })
//
//       // 按行分割缓冲区
//       const lines = buffer.split('\n')
//
//       // 保留最后一个可能不完整的行在缓冲区中
//       buffer = lines.pop()
//
//       // 处理完整的行
//       for (const line of lines) {
//         if (line.startsWith('data: ')) {
//           const data = line.substring(6)
//           if (data === '[DONE]') {
//             // 流结束
//             break
//           }
//
//           try {
//             // 尝试解析JSON数据
//             const parsedData = JSON.parse(data)
//             if (parsedData.content) {
//               fullResponse += parsedData.content
//             }
//           } catch (e) {
//             // 如果不是JSON，直接添加数据
//             fullResponse += data
//           }
//
//           // 实时更新消息内容
//           if (aiMessageIndex < currentMessages.value.length) {
//             currentMessages.value[aiMessageIndex].content = fullResponse
//             // 强制触发Vue的响应式更新
//             currentMessages.value = [...currentMessages.value]
//             scrollToBottom()
//           }
//         }
//       }
//     }
//
//     // 处理缓冲区中剩余的数据
//     if (buffer.startsWith('data: ')) {
//       const data = buffer.substring(6)
//       if (data !== '[DONE]') {
//         try {
//           const parsedData = JSON.parse(data)
//           if (parsedData.content) {
//             fullResponse += parsedData.content
//           }
//         } catch (e) {
//           fullResponse += data
//         }
//
//         // 最终更新消息内容
//         if (aiMessageIndex < currentMessages.value.length) {
//           currentMessages.value[aiMessageIndex].content = fullResponse
//           currentMessages.value = [...currentMessages.value]
//         }
//       }
//     }
//
//     // 流式输出完成
//     isLoading.value = false
//     // 更新会话列表中的标题和预览
//     updateConversationPreview(content, fullResponse)
//
//   } catch (error) {
//     console.error('AI聊天出错:', error)
//     const lastIndex = currentMessages.value.length - 1
//     if (lastIndex >= 0 && !currentMessages.value[lastIndex].isUser) {
//       currentMessages.value[lastIndex].content = '服务器连接出错，请稍后再试。'
//       currentMessages.value = [...currentMessages.value]
//     }
//     isLoading.value = false
//     scrollToBottom()
//     ElMessage.error('请求发送失败')
//   }
// }

// 发送消息
const sendMessage = async () => {
  const content = inputMessage.value.trim()
  if (!content || isLoading.value || !currentConversationId.value) return

  // 添加用户消息 - 使用isUser字段
  const userMessage = {
    content,
    isUser: true // 使用isUser字段
  }
  currentMessages.value.push(userMessage)

  inputMessage.value = ''
  isLoading.value = true
  scrollToBottom()

  try {
    // 调用后端API发送消息
    const res = await Request.post('/chat/send', {}, {
      params: {
        userId: userId.value,
        conversationId: currentConversationId.value,
        message: content
      }
    })

    // 处理响应
    let aiResponse = '';
    if (res && typeof res === 'object') {
      aiResponse = res.content || res.data || '抱歉，我暂时无法理解您的问题，请稍后再试。';
    } else {
      aiResponse = res || '抱歉，我暂时无法理解您的问题，请稍后再试。';
    }

    // 添加AI消息 - 使用isUser字段
    const aiMessage = {
      content: aiResponse,
      isUser: false // 使用isUser字段
    }
    currentMessages.value.push(aiMessage)

    // 更新会话列表中的标题和预览
    updateConversationPreview(content, aiResponse)
  } catch (error) {
    console.error('AI聊天出错:', error)
    currentMessages.value.push({
      content: '服务器连接出错，请稍后再试。',
      isUser: false // 使用isUser字段
    })
  } finally {
    isLoading.value = false
    scrollToBottom()
  }
}

// 更新会话预览和标题
const updateConversationPreview = (userMsg, aiReply) => {
  const index = conversations.value.findIndex(conv => conv.conversationId === currentConversationId.value)
  if (index !== -1) {
    // 更新预览信息
    conversations.value[index].preview = userMsg.length > 20 ? userMsg.substring(0, 20) + '...' : userMsg

    // 如果是新会话，更新标题
    if (conversations.value[index].title === '新会话') {
      conversations.value[index].title = userMsg.length > 20 ? userMsg.substring(0, 20) + '...' : userMsg
    }

    // 把当前会话移到最前面
    const [current] = conversations.value.splice(index, 1)
    conversations.value.unshift(current)

    // 强制刷新列表
    conversations.value = [...conversations.value]
  }
}

// 获取最后一条消息预览
const getLastMessagePreview = (conversation) => {
  if (conversation.aimessages && conversation.aimessages.length > 0) {
    // 过滤掉系统消息，然后获取最后一条消息
    const nonSystemMessages = conversation.aimessages.filter(msg => msg.role !== 'system')
    if (nonSystemMessages.length > 0) {
      const lastMsg = nonSystemMessages[nonSystemMessages.length - 1]
      return lastMsg.content.length > 25 ? lastMsg.content.substring(0, 25) + '...' : lastMsg.content
    }
  }
  // 如果没有消息，使用预览字段
  if (conversation.preview) {
    return conversation.preview
  }
  return '无消息'
}

// 滚动到底部
const scrollToBottom = () => {
  nextTick(() => {
    const chatContainer = document.querySelector('.chat-messages')
    if (chatContainer) {
      chatContainer.scrollTop = chatContainer.scrollHeight
    }
  })
}

// 拖动相关方法
const startDrag = (e) => {
  e.stopPropagation()
  isDragging.value = true
  const rect = e.target.getBoundingClientRect()
  dragOffset.value.x = e.clientX - rect.left
  dragOffset.value.y = e.clientY - rect.top
  document.addEventListener('mousemove', handleDrag)
  document.addEventListener('mouseup', stopDrag)
}

const handleDrag = (e) => {
  if (!isDragging.value) return

  const newLeft = e.clientX - dragOffset.value.x
  const newTop = e.clientY - dragOffset.value.y
  const maxLeft = window.innerWidth - buttonPosition.value.width
  const maxTop = window.innerHeight - buttonPosition.value.height

  buttonPosition.value.left = Math.max(0, Math.min(newLeft, maxLeft))
  buttonPosition.value.top = Math.max(0, Math.min(newTop, maxTop))
}

const stopDrag = () => {
  isDragging.value = false
  document.removeEventListener('mousemove', handleDrag)
  document.removeEventListener('mouseup', stopDrag)
}

// 初始化位置
onMounted(() => {
  buttonPosition.value.left = window.innerWidth - buttonPosition.value.width - 30
  buttonPosition.value.top = window.innerHeight - buttonPosition.value.height - 100
})

// 清理事件监听
onUnmounted(() => {
  document.removeEventListener('mousemove', handleDrag)
  document.removeEventListener('mouseup', stopDrag)
})

// 监听会话切换，自动滚动到底部并聚焦输入框
watch(currentConversationId, (newVal) => {
  if (newVal) {
    scrollToBottom()
    nextTick(() => {
      if (messageInput.value) {
        messageInput.value.focus()
      }
    })
  }
})
</script>

<style scoped>
/* 样式保持不变，增加图片相关样式 */
.ai-assistant {
  position: fixed;
  z-index: 1000;
  pointer-events: none;
}

.ai-button {
  position: fixed;
  width: 60px;
  height: 60px;
  border-radius: 50%;
  background: linear-gradient(135deg, #67C23A, #52b12c);
  box-shadow: 0 4px 12px rgba(103, 194, 58, 0.3);
  display: flex;
  justify-content: center;
  align-items: center;
  cursor: pointer;
  transition: all 0.3s ease;
  pointer-events: auto;
  z-index: 1001;
}

.ai-button:hover {
  transform: scale(1.05);
  box-shadow: 0 6px 16px rgba(103, 194, 58, 0.4);
}

/* AI图标样式 */
.ai-icon {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  object-fit: cover;
}

/* AI头像样式 */
.avatar-img {
  width: 36px;
  height: 36px;
  border-radius: 50%;
  object-fit: cover;
}

.chat-dialog {
  position: fixed;
  width: 900px;
  max-width: 90vw;
  height: 600px;
  background: white;
  border-radius: 12px;
  box-shadow: 0 8px 24px rgba(0, 0, 0, 0.15);
  display: flex;
  flex-direction: column;
  pointer-events: auto;
  z-index: 1000;
  overflow: hidden;
}

.dialog-header {
  padding: 16px 20px;
  background: #f8faf5;
  border-bottom: 1px solid #eee;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-title {
  font-size: 16px;
  font-weight: 600;
  color: #333;
}

.close-btn {
  color: #909399;
  cursor: pointer;
  transition: color 0.2s;
}

.close-btn:hover {
  color: #606266;
}

.dialog-body {
  display: flex;
  flex: 1;
  overflow: hidden;
}

.conversation-list {
  width: 280px;
  border-right: 1px solid #eee;
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

.new-conversation-btn {
  margin: 15px;
}

.conversation-items {
  flex: 1;
  overflow-y: auto;
  padding: 5px 0;
}

.conversation-item {
  padding: 12px 15px;
  cursor: pointer;
  border-bottom: 1px solid #f5f5f5;
  transition: background-color 0.2s;
}

.conversation-item:hover {
  background-color: #f9f9f9;
}

.conversation-item.active {
  background-color: #f0f9eb;
  border-left: 3px solid #67C23A;
}

.conv-title {
  font-size: 14px;
  font-weight: 500;
  margin-bottom: 4px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.delete-conv {
  color: #f56c6c;
  font-size: 16px;
  opacity: 0;
  transition: opacity 0.2s;
}

.conversation-item:hover .delete-conv {
  opacity: 1;
}

.conv-preview {
  font-size: 12px;
  color: #909399;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.chat-area {
  flex: 1;
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

.chat-messages {
  flex: 1;
  padding: 20px;
  overflow-y: auto;
  background-color: #fcfcfc;
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.message {
  display: flex;
  max-width: 85%;
}

.user-message {
  align-self: flex-end;
  flex-direction: row-reverse;
}

.ai-message {
  align-self: flex-start;
}

.message-avatar {
  width: 36px;
  height: 36px;
  border-radius: 50%;
  background-color: #f0f0f0;
  display: flex;
  justify-content: center;
  align-items: center;
  margin-right: 10px;
  flex-shrink: 0;
}

.user-message .message-avatar {
  margin-right: 0;
  margin-left: 10px;
  background-color: #e6f7ee;
}

.message-avatar :deep(.el-icon) {
  font-size: 18px;
  color: #4096ff;
}

.message-content {
  padding: 10px 14px;
  border-radius: 18px;
  line-height: 1.5;
  word-break: break-word;
}

.ai-message .message-content {
  background-color: #f0f0f0;
  color: #333;
  border-top-left-radius: 6px;
}

.user-message .message-content {
  background-color: #67C23A;
  color: white;
  border-top-right-radius: 6px;
}

.message-input {
  padding: 12px 16px;
  border-top: 1px solid #eee;
  display: flex;
  gap: 10px;
}

.message-input :deep(.el-input) {
  flex: 1;
}

.message-input :deep(.el-input.is-disabled .el-input__inner) {
  cursor: not-allowed;
  background-color: #f5f7fa;
}

.send-btn {
  background-color: #67C23A;
  border-color: #67C23A;
  width: 40px;
  height: 40px;
  border-radius: 50%;
  padding: 0;
  display: flex;
  justify-content: center;
  align-items: center;
}

.send-btn:hover {
  background-color: #52b12c;
  border-color: #52b12c;
}

.empty-state {
  flex: 1;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  color: #909399;
  background-color: #fcfcfc;
}

.empty-icon {
  width: 64px;
  height: 64px;
  border-radius: 50%;
  object-fit: cover;
  margin-bottom: 16px;
}

.typing-indicator {
  display: flex;
  gap: 6px;
  padding: 8px 12px;
}

.dot {
  width: 8px;
  height: 8px;
  border-radius: 50%;
  background-color: #999;
  animation: typing 1.4s infinite ease-in-out both;
}

.dot:nth-child(1) { animation-delay: -0.32s; }
.dot:nth-child(2) { animation-delay: -0.16s; }

@keyframes typing {
  0%, 80%, 100% { transform: scale(0); }
  40% { transform: scale(1); }
}

.chat-messages::-webkit-scrollbar,
.conversation-items::-webkit-scrollbar {
  width: 6px;
}

.chat-messages::-webkit-scrollbar-track,
.conversation-items::-webkit-scrollbar-track {
  background: #f1f1f1;
  border-radius: 10px;
}

.chat-messages::-webkit-scrollbar-thumb,
.conversation-items::-webkit-scrollbar-thumb {
  background: #ddd;
  border-radius: 10px;
}

.chat-messages::-webkit-scrollbar-thumb:hover,
.conversation-items::-webkit-scrollbar-thumb:hover {
  background: #ccc;
}

@media (max-width: 768px) {
  .chat-dialog {
    height: 80vh;
    width: calc(100vw - 40px);
  }

  .conversation-list {
    width: 100px;
  }

  .conv-title {
    font-size: 12px;
  }

  .conv-preview {
    display: none;
  }
}
</style>
